<?php

namespace App\Helpers;

class XmlUtil{

    /**
     * 判断字符串是否xml
     * @param string $str
     * @return bool
     */
    public static function xml_parser($str){
        $xml_parser = xml_parser_create();
        if(!xml_parse($xml_parser,$str,true)){
            xml_parser_free($xml_parser);
            return false;
        }else {
            return (json_decode(json_encode(simplexml_load_string($str)),true));
        }
    }

    /**
     * 将xml转为array
     *
     * @param $xml
     * @return mixed|string
     */
    public static function FromXml($xml)
    {
        if(!$xml){
            return '';
        }
        //将XML转为array
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    }

    /**
     * 格式化接口返回数据为数组格式
     * @param string $params
     * @param array $exclude 排除的字段
     * @return array
     */
    public static function paramsToArray($params,$exclude = ['signature','sign']) {
        $result = explode('&',$params);
        $sign_arr = [];
        foreach ($result as $key =>$val){
            $val_arr = explode('=',$val,2);
            $sign_arr[$val_arr[0]] = $val_arr[1];
        }

        foreach ($exclude as $val){
            unset($sign_arr[$val]);
        }

        return $sign_arr;
    }
}
